package com.mycloud.service.impl;

//import com.mycloud.client.ProductClient;
import com.mycloud.dataobject.OrderDetail;
import com.mycloud.dataobject.OrderMaster;
import com.mycloud.dataobject.ProductInfo;
import com.mycloud.dto.CartDTO;
import com.mycloud.dto.OrderDTO;
import com.mycloud.enums.OrderStatusEnum;
import com.mycloud.enums.PayStatusEnum;
import com.mycloud.enums.ResultEnum;
import com.mycloud.exception.OrderException;
import com.mycloud.product.client.ProductClient;
import com.mycloud.product.common.DecreaseStock;
import com.mycloud.product.common.ProductInfoOutput;
import com.mycloud.repository.OrderDetailRepository;
import com.mycloud.repository.OrderMasterRepository;
import com.mycloud.service.OrderService;
import com.mycloud.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by PC on 2019/1/2.
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductClient productClient;


    @Override
    @Transactional
    public OrderDTO createOrder(OrderDTO orderDTO) {
        String orderId = KeyUtil.getUniqueKey();

        // (调用商品服务)
        List<String> idList = orderDTO.getOrderDetailList().stream().map(OrderDetail::getProductId).collect(Collectors.toList());
        List<ProductInfoOutput> productInfoList = productClient.listProductByIdList(idList);
        // （计算总金额）
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderDetail orderDetail: orderDTO.getOrderDetailList()
             ) {
            for (ProductInfoOutput productInfo: productInfoList
                 ) {
                if(productInfo.getProductId().equals(orderDetail.getProductId())){
                    totalAmount = totalAmount.add(productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())));
                    orderDetail.setProductName(productInfo.getProductName());
                    orderDetail.setProductPrice(productInfo.getProductPrice());
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.getUniqueKey());
                    //订单详情入库
                    orderDetailRepository.save(orderDetail);
                }
            }

        }
        //(扣库存)
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e -> new CartDTO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        List<DecreaseStock> decreaseStockList = cartDTOList.stream().map(e -> new DecreaseStock(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productClient.decreaseStock(decreaseStockList);
        // 订单入库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.NEW.getCode());
        orderMaster.setCreateTime(LocalDateTime.now());
        orderMaster.setUpdateTime(LocalDateTime.now());
        orderMaster.setOrderAmount(totalAmount);

        orderMasterRepository.save(orderMaster);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            throw new OrderException(ResultEnum.ORDER_ID_EMPTY);
        }
        Optional<OrderMaster> masterOptional = orderMasterRepository.findById(orderId);
        if (!masterOptional.isPresent()) {
            throw new OrderException(ResultEnum.ORDER_NULL);
        }
        OrderMaster orderMaster = masterOptional.get();
        if (!OrderStatusEnum.NEW.getCode().equals(orderMaster.getOrderStatus())) {
            throw new OrderException(ResultEnum.ORDER_STATUE_ERROR);
        }
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        orderMasterRepository.save(orderMaster);
        OrderDTO target = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, target);
        List<OrderDetail> detailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(detailList)) {
            throw new OrderException(ResultEnum.ORDER_DETAIL_NULL);
        }
        target.setOrderDetailList(detailList);
        return target;
    }
}
